package com.miplus.ccrm.core.service.action;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.*;
import com.miplus.ccrm.core.controller.vo.LabelResVo;
import com.miplus.ccrm.core.controller.vo.action.*;
import com.miplus.ccrm.core.controller.vo.conf.NamesResVo;
import com.miplus.ccrm.core.controller.vo.conf.UserInfoResVo;
import com.miplus.ccrm.core.mapper.ConContactMapper;
import com.miplus.ccrm.core.mapper.FiCreditcasesMapper;
import com.miplus.ccrm.core.mapper.MsgDefineMapper;
import com.miplus.ccrm.core.mapper.model.FiCasesSmsBatchVo;
import com.miplus.ccrm.core.mapper.model.FiCasesSmsVo;
import com.miplus.ccrm.core.pojo.*;
import com.miplus.ccrm.core.mapper.SmsSendphnMapper;
import com.miplus.ccrm.core.security.JCommonData;
import com.miplus.ccrm.core.service.ExportService;
import com.miplus.ccrm.core.service.conf.MsgDefineService;
import com.miplus.ccrm.core.service.conf.SysNamesService;
import com.miplus.ccrm.core.service.crd.FiImportHistService;
import com.miplus.ccrm.core.service.crd.FiTaskService;
import com.miplus.ccrm.core.utils.EnumFiChannel;
import com.miplus.ccrm.sms.JSmsService;
import com.miplus.ccrm.sms.SmsR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
* @author pc
* @description 针对表【sms_sendphn】的数据库操作Service实现
* @createDate 2024-04-25 20:29:32
*/
@Slf4j
@Service
public class SmsSendphnServiceImpl extends MPJBaseServiceImpl<SmsSendphnMapper, SmsSendphn>
    implements SmsSendphnService{
    @Resource
    private FiTaskService fiTaskService;
    @Resource
    private ConContactMapper conContactMapper;
    @Resource
    private MsgDefineMapper msgDefineMapper;
    @Resource
    private FiCreditcasesMapper fiCreditcasesMapper;
    @Resource
    private JSmsService smsService;

    @Resource
    private MsgDefineService msgDefineService;

    @Resource
    private SysNamesService sysNamesService;

    @Resource
    private ExportService exportService;

    @Resource
    private FiImportHistService fiImportHistService;

    @Override
    public IPage<SmsResVo> fiSmsList(JSysUser user, SmsReqVo paras)
    {
        String $usrid = user.getUsrid();
        //2025-05-13
        boolean viewAllCase=JUsrPerm.viewAllFiCase(user);
        boolean viewGrpFiCase = false;
        if(!viewAllCase && user.getMgrgrplist().size()>0)
            viewGrpFiCase = true;

        List<Integer>kidList=new ArrayList<>();
        IPage<SmsResVo> smsResVoPage = selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                SmsResVo.class,
                new MPJLambdaWrapper<SmsSendphn>()
                        .leftJoin("sys_user su on su.usrid = t.usrid")
//                        .leftJoin(MsgDefine.class, MsgDefine::getId, SmsSendphn::getMsgid)
//                        .selectAs(MsgDefine::getName, SmsResVo::getMsgName)
//                        .selectAs("fun_getnames('SMS.STATUS',t.status)", SmsResVo::getStatus)
//                        .selectAs(String.format("fi_starSecu('%s','disstar.phone',t.phn,'')", $usrid), SmsResVo::getPhn)
//                        .selectAs("select g.grpname from sys_grp g where g.grpid=u.groups", SmsResVo::getSendtodept)
                        .select(SmsSendphn::getKid,SmsSendphn::getCrdt, SmsSendphn::getMsg, SmsSendphn::getSmslevel, SmsSendphn::getErrcode,
                                SmsSendphn::getCause, SmsSendphn::getCrmid, SmsSendphn::getMsgid, SmsSendphn::getAppid)
                        .selectAs("CONCAT(su.`NAME`,CONCAT('(',su.usrid,')'))",SmsSendphn::getUsrid)
                        .in(ObjectUtils.isNotNull(paras.getUsrid()), SmsSendphn::getUsrid, paras.getUsrid())
                        .eq(JPubUtils.IsNotEmpty(paras.getStatus()), SmsSendphn::getStatus, paras.getStatus())
                        .eq(JPubUtils.IsNotEmpty(paras.getPhn()), SmsSendphn::getPhn, paras.getPhn())
                        .eq(!viewAllCase && !viewGrpFiCase, SmsSendphn::getUsrid,$usrid)
                        .in(viewGrpFiCase,"su.groups",user.getMgrgrplist())
                        .in(ObjectUtils.isNotNull(paras.getMsgid()), SmsSendphn::getMsgid, paras.getMsgid())
                        .in(ObjectUtils.isNotNull(paras.getSendtodept()), "su.groups", paras.getSendtodept())
//                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), SmsSendphn::getCrdt,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
                        .ge(JPubUtils.IsNotEmpty(paras.getStartdt()), SmsSendphn::getCrdt, paras.getStartdt())
                        .le(JPubUtils.IsNotEmpty(paras.getEnddt()), SmsSendphn::getCrdt, paras.getEnddt())
                        .orderByAsc(SmsSendphn::getKid)
        ).convert(x->{
            kidList.add(x.getKid());
            return x;
        });

        if(kidList!=null&& kidList.size()>0){
            Map<Integer, SmsResVo> smsResVoMap = selectJoinList(SmsResVo.class, new MPJLambdaWrapper<SmsSendphn>()
                    .leftJoin("sys_user su on t.usrid=su.usrid")
                    .leftJoin(MsgDefine.class, MsgDefine::getId, SmsSendphn::getMsgid)
                    .selectAs(MsgDefine::getName, SmsResVo::getMsgName)
                    .selectAs("fun_getnames('SMS.STATUS',t.status)", SmsResVo::getStatus)
                    .selectAs(String.format("fi_starSecu('%s','disstar.phone',t.phn,'%s')", $usrid,ObjectUtils.isNull(paras.getIsExport())?"":"FORCESECU"), SmsResVo::getPhn)
                    .selectAs("(select g.grpname from sys_grp g where g.grpid=su.groups)", SmsResVo::getSendtodept)
                    .select(SmsSendphn::getKid)
                    .in(SmsSendphn::getKid,kidList)
            ).stream().collect(Collectors.toMap(item -> item.getKid(), item -> item));

            smsResVoPage.convert(x->{
                x.setMsgName(smsResVoMap.get(x.getKid()).getMsgName());
                x.setStatus(smsResVoMap.get(x.getKid()).getStatus());
                x.setPhn(smsResVoMap.get(x.getKid()).getPhn());
                x.setSendtodept(smsResVoMap.get(x.getKid()).getSendtodept());
                return x;
            });

        }

        return smsResVoPage;
    }

    @Override
    public CmdResVo fiSmsAdd(String $usrid, SmsAddVo paras)
    {
        //联系人是为了客户端不送明码电话过来，后台取表关联数据
        if(JPubUtils.IsEmpty(paras.getContactnumber())&&
                JPubUtils.IsEmpty(paras.getPhone())){
            throw new ServiceException(EnumRCode.ArgErr.value, EnumRCode.ArgErr.name);
        }
        String phone=paras.getPhone();
        //如果有联系人ID，优先以联系人为准
        if(JPubUtils.IsNotEmpty(paras.getContactnumber())){
          ConContact contact=conContactMapper.selectById(paras.getContactnumber());
          phone=contact.getPhone();
        }

        //maxSmsSendCount:客户单天发送的最大数量。 自动
        //smsSendInterval：单电话具体上次发送的间隔时间。
        int maxSmsSendCount = 9999999, smsSendInterval = 0;

        String tmpStr = sysNamesService.getNamesDsc("SYS.PARA","MAX_SMS_COUNT");
        if(StringUtils.isNotEmpty(tmpStr)){
            maxSmsSendCount = JPubUtils.StringToInt(tmpStr);
        }
        tmpStr = sysNamesService.getNamesDsc("SYS.PARA","SMS_SEND_INTERVAL");
        if(StringUtils.isNotEmpty(tmpStr)){
            smsSendInterval = JPubUtils.StringToInt(tmpStr);
        }
        String clid=paras.getClid();
        if(JPubUtils.IsEmpty(clid)){
            clid="SYS_SMS";
        }
        SmsDaySendInfoVo smsDaySendInfoVo = getBaseMapper().getCurrentDaySmsInfo(paras.getContactnumber(), phone);
        if( smsDaySendInfoVo != null){
            if( smsDaySendInfoVo.getSendcnt() >= maxSmsSendCount)
                return new CmdResVo(-1, String.format("该客户今天发送短信条数已达限定值%d条，今天不再允许发送",maxSmsSendCount));
            if(smsSendInterval>0 && ObjectUtils.isNotNull(smsDaySendInfoVo.getLastsenddt()))
            {
                Date now = new Date();
                Long diffMinutes  =  (now.getTime() -  smsDaySendInfoVo.getLastsenddt().getTime())/(60 * 1000);
                log.info("fiSmsAdd diffMinuts:{}, SendInterval:{}, now:{}, senddt:{}",diffMinutes,smsSendInterval,now.getTime(), smsDaySendInfoVo.getLastsenddt().getTime());
                if( diffMinutes < smsSendInterval )
                    return new CmdResVo(-1, String.format("同一天同一客户同一手机号码发送短信的时间间隔必须大于%d分钟",smsSendInterval));
            }
        }
        //解析报文参数
        String[] placeholdersArray = smsMessageDecryption($usrid,Long.valueOf(String.valueOf(paras.getFicaseid())), paras.getSmstext());
        if(placeholdersArray==null){
            throw new ServiceException(EnumRCode.CmdFail.value,"SmsAddVo:"+paras.getFicaseid());
        }
        String smsText = replacePlaceholders(paras.getSmstext(), placeholdersArray);

        Integer tasknumber=0;
        if(JPubUtils.IsNotEmpty(paras.getFicaseid())) {
            tasknumber=fiTaskService.addTask($usrid, clid, paras.getFicaseid(),EnumFiChannel.Sms.value,
                    paras.getContactnumber(),phone,"WAITSEND",smsText);
        }

//        String ipaddr=JPubUtils.getLocalIpAddr();

        SmsR smsR=smsService.SendSmsArray(paras.getMsgid(),phone,placeholdersArray);

//        SmsR smsR=smsService.SendSms(ipaddr,getGlblSeqNo(),phone,paras.getSmstext());

        if(smsR.getCode()==0){
            SaveSms(phone,smsText,paras.getMsgid(),tasknumber,"CCRM01",$usrid,2,"0", smsR.getRefID());
            fiTaskService.lambdaUpdate().set(FiTask::getResult,"发送成功").eq(FiTask::getTasknumber,tasknumber).update();
        }
        else{
            SaveSms(phone,smsText,paras.getMsgid(),tasknumber,"CCRM01",$usrid,3,smsR.getCode().toString(),"");
            fiTaskService.lambdaUpdate().set(FiTask::getResult,"发送失败").eq(FiTask::getTasknumber,tasknumber).update();
            throw new ServiceException(EnumRCode.CmdFail.value, smsR.getMessage());
        }

        return new CmdResVo(0,"1");
    }

    @Override
    public SmsAddBatchReqVo fiSmsAddBatch(JSysUser user, SmsAddBatchReqVo paras) {

        //列表初始化
        if(paras.getIsView()==null){

            boolean hasSecuPhnPermit = JUsrPerm.hasPermission(user,"disstar.phone");

            // 获取 联系人
            List<Integer> credid = paras.getList().stream().map(FiCasesSmsBatchVo::getCreditcaseid).collect(Collectors.toList());

//            Long caseCount = fiCreditcasesMapper.selectCount(new QueryWrapper<FiCreditcases>()
//                    .in("creditcaseid", credid)
//                    .gt("overdue_totalamt", 0)
//            );
            List<FiCasesSmsBatchVo> phoneList = fiCreditcasesMapper.getPhoneList(credid);

            if(credid.size()!=phoneList.size()){
                paras.setIsOverdue(true);
                return paras;
            }

            phoneList.forEach(x->{
                if(!hasSecuPhnPermit)
                {
                    if(JPubUtils.IsNotEmpty(x.getPhone()) && x.getPhone().length() > 6 ){
                        String phn = x.getPhone().substring(0,3) + "***" + x.getPhone().substring(x.getPhone().length() -3);
                        x.setPhone(phn);
                    }
                }
            });
            paras.setList(phoneList);
            paras.setIsOverdue(false);
            return paras;
        }

        // 补充预览数据
        if(paras.getIsView()==true){

            for (FiCasesSmsBatchVo smsBatchVo : paras.getList()) {

                // 权限校验
                List<LabelResVo> msgTmpList = msgDefineService.getMsgTmpList(String.valueOf(smsBatchVo.getCreditcaseid()), String.valueOf(smsBatchVo.getContactnumber()), user.getUsrid(), "2", 1, smsBatchVo.getMsgid());//
                if(ObjectUtils.isEmpty(msgTmpList)){
                    smsBatchVo.setSmstxtPr(null);
                    smsBatchVo.setMsgDsc("没有权限发送");
                    smsBatchVo.setMsgid(null);
                    continue;
                }
                if(smsBatchVo.getIsstopcase()>0){
                    smsBatchVo.setSmstxt(null);
                    smsBatchVo.setMsgid(null);
                    smsBatchVo.setSmstxtPr(null);
                    continue;
                }

                SmsSendPreviewResVo resVo = smsSendPreview(user.getUsrid(), new SmsSendPreviewReqVo(smsBatchVo.getCreditcaseid(),
                        smsBatchVo.getMsgid()));
                smsBatchVo.setSmstxt(resVo.getSmstxt());
                smsBatchVo.setSmstxtPr(resVo.getSmstxtPr());
            }

        }

        // 发送短信
        if(paras.getIsView()==false){

            for (FiCasesSmsBatchVo smsBatchVo : paras.getList()) {
                if(smsBatchVo.getMsgid()==null|| smsBatchVo.getIsstopcase()>0){
                    continue;
                }
                SmsAddVo smsAddVo=new SmsAddVo();
                smsAddVo.setFicaseid(smsBatchVo.getCreditcaseid());
                smsAddVo.setContactnumber(Long.valueOf(smsBatchVo.getContactnumber()));
                smsAddVo.setSmstext(smsBatchVo.getSmstxt());
                smsAddVo.setMsgid(smsBatchVo.getMsgid());
                fiSmsAdd(user.getUsrid(), smsAddVo);
            }
        }

        paras.setIsOverdue(false);
        return paras;
    }

    @Override
    public SmsSendPreviewResVo smsSendPreview(String $usrid,SmsSendPreviewReqVo paras) {

        SmsSendPreviewResVo resVo=new SmsSendPreviewResVo();
        MsgDefine dbMsgDefine = msgDefineMapper.selectById(paras.getMsgid());
        resVo.setMsgid(paras.getMsgid());
        resVo.setSmstxt(dbMsgDefine.getSmstxt());

        //解析报文参数
        String[] placeholdersArray = smsMessageDecryption($usrid,Long.valueOf(String.valueOf(paras.getFicaseid())), dbMsgDefine.getSmstxt());
        if(placeholdersArray==null){
            throw new ServiceException(EnumRCode.CmdFail.value,"smsSendPreview:"+paras.getFicaseid());
        }
        String smsText = replacePlaceholders(dbMsgDefine.getSmstxt(), placeholdersArray);
        resVo.setSmstxtPr(smsText);
        return resVo;

    }

    @Override
    public CmdResVo repayApplySms(String ficaseid,String $userid,Long contactnumber,String phone,
                                  String name,String gender,
                                  String amt,String url) {

        //尊敬的{1}{2}，您申请的借款已逾期，应还金额为{12}。请点击短信链接通过支付宝还款{13}。如有问题，详询95173。
        String sex=gender;
        if(gender==null){
            sex="先生/女士";
        }else {
            sex="1".equals(gender)?"先生":"女士";
        }

        String[] array={name,sex,amt,url};
        String clid="SYS_SMS";
        String msgId="NDCSS16";//短信模板号
        String smsText="尊敬的"+name+sex+"，您申请的借款已逾期，应还金额为"+amt+"。请点击短信链接通过支付宝还款"+url+"。如有问题，详询95173。";

        log.info("msgId{},senSMS:{}",msgId,smsText);
        Integer tasknumber=0;
        if(JPubUtils.IsNotEmpty(ficaseid)) {
            tasknumber=fiTaskService.addTask($userid, clid, Integer.valueOf(ficaseid),EnumFiChannel.Sms.value,
                    contactnumber,phone,"WAITSEND",smsText);
        }

        SmsR smsR=smsService.SendSmsArray(msgId,phone,array);

        if(smsR.getCode()==0){
            SaveSms(phone,smsText,msgId,tasknumber,"CCRM01",$userid,2,"0", smsR.getRefID());
            fiTaskService.lambdaUpdate().set(FiTask::getResult,"发送成功").eq(FiTask::getTasknumber,tasknumber).update();
        }
        else{
            SaveSms(phone,smsText,msgId,tasknumber,"CCRM01",$userid,3,smsR.getCode().toString(),"");
            fiTaskService.lambdaUpdate().set(FiTask::getResult,"发送失败").eq(FiTask::getTasknumber,tasknumber).update();
            throw new ServiceException(EnumRCode.CmdFail.value, "SmsFail:"+smsR.getCode().toString());
        }

        return new CmdResVo(0,"1");
    }


    public String replacePlaceholders (String template,String[] values){
        String regex = "\\$\\{([^}]+)\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(template);

        // 使用 List 来收集匹配的结果，然后转换为数组
        List<String> placeholders = new ArrayList<>();
        while (matcher.find()) {
            placeholders.add(matcher.group(1)); // group(1) 捕获了括号内的内容
        }

        // 将 List 转换为数组（如果需要的话）
        String[] placeholderArray = placeholders.toArray(new String[0]);

        // 确保 placeholders 和 values 数组的长度相同
        if (placeholderArray.length != values.length) {
            throw new IllegalArgumentException("Placeholders and values arrays must have the same length.");
        }

        // 创建一个 StringBuilder 来存储替换后的字符串
        StringBuilder result = new StringBuilder(template);

        // 遍历数组，进行替换
        for (int i = 0; i < placeholderArray.length; i++) {
            String placeholder = "${" + placeholderArray[i] + "}";
            String value = values[i];
            if(value==null){
                value="";
            }
            // 使用 replace 方法进行替换
            // 注意：如果值中包含特殊字符（如正则表达式中的元字符），可以考虑使用 replaceAll 和 escape 特殊字符
            int index = result.indexOf(placeholder);
            while (index != -1) {
                result.replace(index, index + placeholder.length(), value);
                index = result.indexOf(placeholder, index + value.length());
            }
        }

        // 输出替换后的字符串
//        System.out.println(result.toString());

        return result.toString();
    }


    public String[] smsMessageDecryption(String $usrid,Long fiCaseId,String smsText){
        LinkedList<String> placeholders=new LinkedList<>();
        // 获取全文信息 解析 占位符
        /**
         * cust_name 姓名
         * gender   性别
         * repay_date  日期
         * prd_name   产品名称
         * beoverdueDay  逾期天数
         * beoverdueAmount 逾期金额
         * pre_repay_date  应还款日
         * pre_repay_amount  应还款金额
         * product2   产品
         * merchant_abbreviation  商户简称
         *  外显号码
         */


        // 定义正则表达式来匹配占位符
        String regex = "\\$\\{(\\w+)\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(smsText);

        FiCasesSmsVo casesSmsInfo = fiCreditcasesMapper.getCasesSmsInfo(fiCaseId);
        if(casesSmsInfo==null){
            return null;
        }

        // 计数器
        int placeholderCount = 0;

        // 遍历匹配结果
        while (matcher.find()) {
            switch (matcher.group(1)){
                case "cust_name":
                    placeholders.add(casesSmsInfo.getCustname());
                    break;
                case "gender":
                    String sex=casesSmsInfo.getGender();
                    if(casesSmsInfo.getGender()==null){
                        sex="先生/女士";
                    }else {
                        sex="1".equals(casesSmsInfo.getGender())?"先生":"女士";
                    }
                    placeholders.add(sex);
                    break;
                case "repay_date":
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    placeholders.add(sdf.format(new Date()));//当前日期
                    break;
                case "prd_name":
                case "product2":
                    placeholders.add(casesSmsInfo.getProductName());
                    break;
                case "beoverdueDay":
                    placeholders.add(String.valueOf(casesSmsInfo.getMthsDay()));
                    break;
                case "beoverdueAmount":
                    if(casesSmsInfo.getOverdueTotalamt().equals(BigDecimal.ZERO)){
                        placeholders.add(null);
                    }else {

                        placeholders.add(String.valueOf(casesSmsInfo.getOverdueTotalamt().setScale(2, RoundingMode.HALF_UP)));
                    }
                    break;
                case "pre_repay_date":
                    if(casesSmsInfo.getRepayDays()==null){
                        placeholders.add(null);
                    }else {
                        SimpleDateFormat rd = new SimpleDateFormat("yyyy-MM-dd");
                        placeholders.add(rd.format(casesSmsInfo.getRepayDays()));
                    }
                    break;
                case "pre_repay_amount":
                    if(casesSmsInfo.getRemindRepayPrincipal()==null
                            ||
                            casesSmsInfo.getRemindRepayPrincipal().equals(BigDecimal.ZERO)){
                        placeholders.add(null);
                    }else{
                        placeholders.add(String.valueOf(casesSmsInfo.getRemindRepayPrincipal().setScale(2, RoundingMode.HALF_UP)));
                    }
                    break;
                case "merchant_abbreviation":
                    placeholders.add(casesSmsInfo.getMerchantName());
                    break;
                case "workId":
                    String employeeid = fiCreditcasesMapper.getEmployeeid($usrid);
                    if(employeeid==null){
                        placeholders.add(null);
                    }else{
                        placeholders.add(employeeid);
                    }
                    break;
            }
            // 每次找到匹配项时，增加计数器
            placeholderCount++;
        }

        if(placeholders==null||
                placeholderCount!=placeholders.size()){
            throw new ServiceException(EnumRCode.CmdFail.value,"SmsAddVo:"+fiCaseId);
        }

        return placeholders.toArray(new String[0]);
    }

    @Override
    public CmdResVo fiSmsSendCode(String usrid, JCommonData jCommonData)
    {
        String mobile=baseMapper.getUsrMobile(usrid);
        if(JPubUtils.IsEmpty(mobile)){
            throw new ServiceException(EnumRCode.NoFindMobile.value, EnumRCode.NoFindMobile.name);
        }

        String smstxt="您的验证码为:{str10_0},该验证码5分钟内有效，请勿泄露于他人。";
        MsgDefine define=msgDefineMapper.selectById("SMS_VCODE");
        if(define!=null) {
            smstxt=define.getSmstxt();
        }
        Random rand=new Random();
        Integer num=rand.nextInt(900000)+100000;
        String sendtxt=smstxt.replace("{str10_0}",num.toString());
        sendtxt=sendtxt.replace("{STR10_0}",num.toString());

        String ipaddr=JPubUtils.getLocalIpAddr();
        SmsR smsR=smsService.SendSms(ipaddr,getGlblSeqNo(),mobile,sendtxt);

        if(smsR.getCode()==0){
            jCommonData.SetUsrSmsVCode(usrid, num.toString());
            SaveSms(mobile,sendtxt,"SMS_VCODE",0,"CCRM02",usrid,2,"0", smsR.getRefID());
        }
        else{
            SaveSms(mobile,sendtxt,"SMS_VCODE",0,"CCRM02",usrid,3,smsR.getCode().toString(),"");
            throw new ServiceException(EnumRCode.CmdFail.value, "SmsFail:"+smsR.getCode().toString());
        }

        return new CmdResVo(1);
    }

    private int SaveSms(String phone,String smstxt,String msgid,Integer tasknumber,
                        String appid,String usrid,Integer status,String code,String refId)
    {
        SmsSendphn sms=new SmsSendphn();
        sms.setPhn(phone);
        sms.setMsg(smstxt);
        sms.setMsgid(msgid);
        if(tasknumber>0) {
            sms.setCrmid(tasknumber.toString());
        }
        sms.setStatus(status); //1=待发送,2=成功，3=失败
        if(status==3){
            sms.setErrcode(code);
            sms.setCause("Fail");
        }else{
            sms.setErrcode("0");
            sms.setCause("Success");
            sms.setRefid(refId);
        }
        sms.setAppid(appid);
        sms.setSmslevel(100);
        sms.setCrdt(new Date());
        sms.setSenddt(new Date());
        sms.setUsrid(usrid);

        return baseMapper.insert(sms);
    }

    private String getGlblSeqNo()
    {
        Random rand=new Random();
        Integer r=rand.nextInt(90000)+10000;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return String.format("%s%d",sdf.format(new Date()),r);
    }

    @Override
    public CmdResVo expSmsList(JSysUser user, SmsReqVo paras, HttpServletResponse response)
    {
        //如果是下载，需要强制加密。
        paras.setIsExport(1);
        IPage<SmsResVo> pages = fiSmsList(user,paras);
        ArrayList arr=new ArrayList();

        String exptempid=JPubUtils.getExpTempID(paras.getExpfilename(),"短信发送列表");

        String filename=JPubUtils.getExpFileName(
                paras.getExpfilename(),exptempid
        );
        pages.convert(u->{
            HashMap map=JPubUtils.toExportMap(u);
            if(map!=null) arr.add(map);
            return u;
        });
        CmdResVo resVo=exportService.ToExcel(
                response,
                arr,
                paras.getExpidlist(),
                paras.getExpnamelist(),
                filename,
                user.getUsrid()
        );

        int okcount=resVo.getCount();
        if(okcount>0){
            fiImportHistService.AddExportHist(
                    resVo.getKeyId(),
                    user.getUsrid(),
                    exptempid,
                    filename,
                    okcount
            );
        }
        return resVo;
    }
}




